<template>
  <el-dialog :title="dialogTitle" :visible.sync="showDialog_" custom-class='dialog_right dialogScroll_add MkAddHomePage' top="0%" @close='closeDialog("addForm")' @open='openDialog' >
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-200)+'px'}]">
      <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="80px" element-loading-text="上传中">
        <input type="text" style="display:none" />
        <el-form-item label="名称" prop='name'>
          <el-input v-model="addForm.formItem.name" placeholder='请输入名称（必填）'  size="" :maxlength=5></el-input>
        </el-form-item>
        <el-form-item label="上级分类" v-if="(parentObj && parentObj.name)|| (currentObj && currentObj.parentName)">
          {{parentObj?parentObj.name:currentObj.parentName}}
        </el-form-item>
        <el-form-item label="是否显示" prop='status'>
          <el-radio-group v-model="addForm.formItem.status">
            <el-radio label="ENABLE">是</el-radio>
            <el-radio label="DISABLE">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop = 'weight'>
          <el-input v-model="addForm.formItem.weight" placeholder="请输入排序（必填）"></el-input>
        </el-form-item>
        <el-form-item label="链接" prop="link" v-if="parentObj || (currentObj && currentObj.appCategoryStatus == 'H5')">
          <el-input v-model="addForm.formItem.link" placeholder="请输入链接（必填）"></el-input>
        </el-form-item>
        <el-form-item label="功能图标" prop="imageId">
          <el-upload
                      accept=".jpeg, .jpg, .png, .gif"
                     class="avatar-uploader" action="/upload/image.json"
                      :show-file-list="false"
                      :on-success="handleSuccess_function"
                      :before-upload="beforeAvatarUpload"
                      name="image">
            <img v-if="dialogImageUrl_function" :src="dialogImageUrl_function" class="avatar" >
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="首页图标" prop="homeImageId">
          <el-upload
            name="image"
            class="avatar-uploader"
            action="/upload/image.json"
            list-type="picture-card"
            accept=".jpeg, .jpg, .png, .gif"
            :file-list = 'fileList_home'
            :on-success="handleSuccess_home"
            :on-remove="handleRemove_home">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer footerStyle">
      <el-button type="primary" class="btn-primary"  :disabled = "isSubmitBtnDisabled" @click='submitForm("addForm")' v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
      <el-button type='primary' class='btn-cancel' @click="showDialog_ = false" size=''>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import homePageService from '../../../services/homePage'
import {mapState} from 'vuex'
export default {
  name: 'MkAddHomePage',
  components: {

  },
  props: ['showDialog', 'parentObj', 'currentObj'],
  computed: mapState({
    bodyHeight: state=> state.global.bodyHeight,
  }),
  methods: {
    handleRemove_home(file,fileList) {
      let fileId = file.fileId?file.fileId: file.response.data.fileId;
      homePageService.deleteFileServer({fileId:fileId},() => {
        this.$message.success('删除成功');
        this.fileList_home = fileList;
      })
    },
    beforeAvatarUpload(file) {
    },
    handleSuccess_function(res, file) {
      this.dialogImageUrl_function = URL.createObjectURL(file.raw);
      this.addForm.formItem.imageId = res.data.fileId;
      this.$refs['addForm'].validateField('imageId');
    },
    handleSuccess_home(res, file) {
      this.fileList_home = [file];
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.dialogImageUrl_function = '';
      this.fileList_home = [];
      var form = this.addForm.formItem;
      for (let i in form) {
        if(i == 'status') {
          form[i] = 'ENABLE';
        }else{
          form[i] = '';
        }
      }
      this.$emit('closeDialog', this.isRefresh);
    },
    openDialog() {
      this.isRefresh = 'no';
      this.isSubmitBtnDisabled = false;
      //编辑的时候
      if (this.currentObj) {
        this.dialogTitle = '编辑分类';
        var form = this.addForm.formItem;
        var currentObj = this.currentObj;
        form.name = currentObj.name;
        form.status = currentObj.status;
        form.id = currentObj.id;
        form.imageId = currentObj.image? currentObj.image.fileId:'';
        form.siteId = currentObj.siteId;
        form.weight = currentObj.weight;
        form.link = currentObj.link;

        this.dialogImageUrl_function = currentObj.image? currentObj.image.accessUrl: '';
        if(currentObj.homeImage) {
          this.fileList_home = [{url:currentObj.homeImage.accessUrl,fileId: currentObj.homeImage.fileId}];
        }

      }
      //添加的时候
      if(this.parentObj) {
        let form = this.addForm.formItem;
        form.siteId = this.parentObj.siteId;
        form.parentId = this.parentObj.id;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.fileList_home.length>0) {
              let item = this.fileList_home[0];
              this.addForm.formItem.homeImageId = item.fileId?item.fileId:item.response.data.fileId;
          }else{
            this.addForm.formItem.homeImageId = '';
          }
          this.fullscreenLoading = true;
          this.isSubmitBtnDisabled = true;
          if (this.currentObj) {
            homePageService.editHomePageServer(this.addForm.formItem, (data) => {
              this.$message({
                type: 'success',
                message: '编辑成功'
              });
              this.isRefresh = 'yes';
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            }, (data) => {
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          } else {
            homePageService.addHomePageServer(this.addForm.formItem, (data) => {
              this.$message({
                type: 'success',
                message: '添加成功'
              });
              this.isRefresh = 'yes';
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            }, (data) => {
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }
        }
      })
    }
  },
  watch: {
    showDialog: function(value) {
      this.showDialog_ = value;
    },
  },
  data() {
    var validateSort = (rule, value, callback) => {
      let val = (value + '').trim();
      if (val === '') {
        callback(new Error('请输入排序'));
      } else {
        let reg = /^[1-9]\d{0,3}$/;
        if (!reg.test(val)) {
          callback(new Error('只能输入整数，最多4位'));
        }
        callback();
      }
    };
    var validateLink = (rule, value, callback) => {
      let val = value .trim();
      if (val === '') {
        callback(new Error('请输入链接'));
      } else {
        callback();
      }
    };
    var validateName = (rule, value, callback) => {
      let val = value .trim();
      if (val === '') {
        callback(new Error('请输入地区名称'));
      } else {
        callback();
      }
    };
    return {
      fileList_home: [],
      dialogImageUrl_function: '',
      dialogTitle: '添加分类',
      isSubmitBtnDisabled: false,
      fullscreenLoading: false,
      isRefresh: 'no',
      showDialog_: this.showDialog,
      addForm: {
        formItem: {
          imageId: '',
          homeImageId:'',
          status: 'ENABLE',
          link: '',
          name: '',
          siteId: '',
          weight: '',

          parentId: '',//添加用到
          id: ''//编辑用到
        },
        rules: {
          name:{validator:validateName,trigger:'change'},
          weight: {validator: validateSort,trigger:'change'},
          link:{validator:validateLink,trigger:'change'},
          imageId: {required: true,message:'请上传功能图标'},
//          homeImageId: {required: true,message:'请上传首页图标'}
        }
      }

    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
@import '../../../assets/style/main.less';

.MkAddHomePage {
  .avatar-uploader {
    .el-upload-list--picture-card {
      position: absolute;
      z-index: 10;
    }
    .el-upload:hover {
      border-color: @primaryColor;
    }
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      height: 146px;
      width: 146px;
    }
    .el-upload--picture-card {
      background: white;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 146px;
      height: 146px;
      line-height: 146px;
      text-align: center;
    }
  }
}
</style>
